03. Using malloc and free

ND213 C03 L03 02.1 Using Malloc And Free HS

So far we only considered primitive data types, whose storage space requirement was already fixed at compile time and could be scheduled with the building of the program executable. However, it is not always possible to plan the memory requirements exactly in advance, and it is inefficient to reserve the maximum memory space each time just to be on the safe side. C and C++ offer the option to reserve memory areas during the program execution, i.e. at runtime. It is important that the reserved memory areas are released again at the "appropriate point" to avoid memory leaks. It is one of the major challenges in memory management to always locate this "appropriate point" though.

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: jupyter-lab
  • Opened files (when workspace is loaded): n/a

Quiz : Dynamic Memory Management with malloc , calloc , resize and free

Question 1: Match the code snippets to the respective comments

#include <stdio.h> 
#include <stdlib.h> 

int main()
{
    // (X)
    int *m = (int*)malloc(sizeof(int)); 
    m = NULL; 

    // (Y)
    int *n = (int*)malloc(sizeof(int)); 
    free(n);
    *n = 23;

    // (Z)
    char *o;
    *o = 'a'; 

    return 0;
}

Comments:

  1. uses a dangling pointer
  2. uses an uninitialized pointer
  3. generates a memory leak

In the code above, there are three snippets marked with X, Y, and Z. Below the code there are three comments. Match the code snippets to the respective comments. Which pairing of comments and code snippets is the correct one?

SOLUTION: X-3, Y-1, Z-2

Question 2 : Problems with pointers

int *f1(void)
{
    int x = 10;
    return (&x);
}

int *f2(void)
{
    int *px;
    *px = 10;
    return px;
}

int *f3(void)
{
    int *px;
    px = (int *)malloc(sizeof(int));
    *px = 10;
    return px;
}

Which of the functions above is likely to cause pointer-related problems?

SOLUTION: `f1` and `f2`

Outro

ND213 C03 L03 02.3 Using Malloc And Free HS